package com.elong.android.specialhouse.utils;

import android.content.Context;
import android.text.InputFilter;
import android.text.Spanned;
import android.widget.EditText;

import com.elong.android.specialhouse.R;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.HashMap;

public class ElongValidator {
    public final static int RULE_NUMBER = 0;
    public final static int RULE_TELNUMBER = 1;
    public final static int RULE_NAME = 2;
    public final static int RULE_SPECIALCHARACTER = 3;
    public final static int RULE_LIMITWORDS = 4;
    public final static int RULE_CREDITCARD_TYPE = 5;

    public final static int RULE_HONGKANGANDMACAOCUSTOMERNAME = 21;
    public final static int RULE_NOTSAMENAME = 22; // 新添规则，入住人名字不能重复

    public final static int RULE_HOTEL_BOOKABLEDAYS = 10;
    public final static int RULE_HOTEL_20DAYS = 11;
    public final static int RULE_EMAIL = 12;
    public final static int RULE_GROUPON_EMAIL = 13;
    public final static int RULE_INVOICE_ADDRESS = 14;

    public final static String REGEX_NUMBER = "^[0-9]+$";
    // 新号段增加 如 "14" 改为只要是以1 开头的校验
    // public final static String REGEX_TELNUMBER =
    // "^(13[0-9]|15[0-9]|18[0-9])\\d{8}";
    public final static String REGEX_TELNUMBER = "^(1[0-9])\\d{9}";
    public final static String REGEX_NAME = "^[/a-zA-Z\u4e00-\u9fa5]+$";

    // 验证码规则
    public final static String REGEX_VERIFY_CODE = "^\\d{6}$";
    /**
     * 在REGEX_NAME基础上允许*
     */
    public final static String REGEX_NAME_WITH_XINGHAO = "^[*/a-zA-Z\u4e00-\u9fa5]+$";
    public final static String REGEX_HKANDMACAONAME = "^[/a-zA-Z]+$";

    public static String CHARACTER_LIMITSTRING = "!@#$%^&*()_-+={}[]|\"':;?/>.<,~`0123456789～！×（）……＋|＝、〔〕｛｝：“；‘《》？，。、0123456789";
    /**
     * 在CHARACTER_LIMITSTRING基础上去除了*限制
     */
    public static String CHARACTER_LIMITSTRING_WITHOUT_XINGHAO = "!@#$%^&()_-+={}[]|\"':;?/>.<,~`0123456789～！×（）……＋|＝、〔〕｛｝：“；‘《》？，。、0123456789";
    public static String CHARACTER_SpecialStr = "!@#$%^&*+|~;[]{}:;.<>?～@#￥％&×……＋|＝〔〕｛｝；《》？";
    public static String CHARACTER_LIMITSTRING_CITY = null;

    public static String CHARACTER_Card15 = "/^[1-9]\\d{7}((0\\d)|(1[0-2]))(([0|1|2]\\d)|3[0-1])\\d{3}$/";
    // 身份证正则表达式(18位)
    public static String CHARACTER_Card18 = "/^[1-9]\\d{5}[1-9]\\d{3}((0\\d)|(1[0-2]))(([0|1|2]\\d)|3[0-1])\\d{4}$/";

    // public final static String WORDS_LIMITSTRING =
    // getString(R.string.rule_limit_word);

    public static boolean checkStringWithRegex(String s, String conditions) {
        return s.matches(conditions);
    }

    /**
     * 验证是否含非法字符
     *
     * @param s
     * @return true=含有非法字符
     */
    public static boolean checkStringContainsIllegalWord(String s) {
        for (int len = CHARACTER_LIMITSTRING.length(), i = 0; i < len; i++) {
            if (s.indexOf(CHARACTER_LIMITSTRING.charAt(i)) >= 0)
                return true;
        }
        return false;
    }

    public static boolean checkStringWithLimitCharacter(String s, String conditions) {
        int l1 = s.length();
        int l2 = conditions.length();
        for (int i = 0; i < l1; i++) {
            char c = s.charAt(i);
            for (int j = 0; j < l2; j++) {
                if (c == conditions.charAt(j)) {
                    return true;
                }
            }
        }
        return false;

    }

    public static boolean checkStringWithLimitWords(String s, String conditions) {
        String[] wordarray = conditions.split(",");

        int len = wordarray.length;
        for (int i = 0; i < len; i++) {

            if (s.toLowerCase().equals(wordarray[i].toLowerCase())) {
                return true;
            }
        }
        return false;

    }

    public final static String getStringFromFile(Context context, int rawid, String key) {

        try {
            InputStream is = context.getResources().openRawResource(rawid);

            BufferedReader reader = new BufferedReader(new InputStreamReader(is, "utf-8"));
            HashMap<String, String> table = new HashMap<String, String>();
            String line = null;
            while (true) {
                line = reader.readLine();

                if (line != null) {
                    line = line.trim();
                    int flag = line.indexOf("=");

                    table.put(line.substring(0, flag), line.substring(flag + 1, line.length()));
                } else {
                    break;
                }
            }
            return table.get(key);
            // result = haspmap.get(key);
        } catch (Exception e) {
            // Log.e(TAG, "load data failed",e);
        }
        return "";
    }

    public static void setSpecialCharacters(Context context) {
        CHARACTER_LIMITSTRING = getStringFromFile(context, R.raw.stringtable, "specialcharacters");
        CHARACTER_LIMITSTRING_CITY = getStringFromFile(context, R.raw.stringtablecitylimit, "specialcharacterscity");
    }

    /**
     * 验证身份证号是否符合规则
     *
     * @param text 身份证号
     * @return
     */
    public static boolean personIdValidation(String text) {
        String regx = "[0-9]{17}x";
        String reg = "[0-9]{17}X";
        String reg1 = "[0-9]{15}";
        String regex = "[0-9]{18}";
        return text.matches(regx) || text.matches(reg1) || text.matches(regex) || text.matches(reg);
    }

    /**
     * 验证是否是大陆手机号
     *
     * @param text
     * @return
     */
    public static boolean isInlandPhone(String text) {
        String regex = "^(1[0-9])\\d{9}";
        return checkStringWithRegex(text, regex);
    }

    /**
     * 验证密码格式是否正确
     *
     * @param text
     * @return
     */
    public static boolean isPassword(String text) {
        String regex = "^[A-Za-z0-9]{6,15}$";
        return checkStringWithRegex(text, regex);
    }

    /**
     * 验证验证码格式是否正确
     *
     * @param text
     * @return
     */
    public static boolean isVerifyCode(String text) {
        String regex = "\\d{6}";
        return checkStringWithRegex(text, regex);
    }

    /**
     * 验证昵称格式是否正确
     *
     * @param text
     * @return
     */
    public static boolean isNickName(String text) {
        String regex = "^[/a-zA-Z\u4e00-\u9fa5]{1,10}$";
        return checkStringWithRegex(text, regex);
    }

    /**
     * 验证入住人格式是否正确
     *
     * @param text
     * @return
     */
    public static boolean isCheckInPerson(String text) {
        String regex = "^[/a-zA-Z\u4e00-\u9fa5]{1,20}$";
        return checkStringWithRegex(text, regex);
    }
    /**
     * 验证电子邮箱格式是否正确
     *
     * @param text
     * @return
     */
    public static boolean isEmail(String text) {
        String regex = "[\\w!#$%&'*+/=?^_`{|}~-]+(?:\\.[\\w!#$%&'*+/=?^_`{|}~-]+)*@(?:[\\w](?:[\\w-]*[\\w])?\\.)+[\\w](?:[\\w-]*[\\w])?";
        return checkStringWithRegex(text, regex);
    }

    /**
     * 控制编辑框只能输入汉字或者英文
     *
     * @param editText
     * @return
     */
    public static void CanOnlyInputZhAndEn(EditText editText) {
        editText.setFilters(new InputFilter[]{new InputFilter() {
            @Override
            public CharSequence filter(CharSequence source, int start, int end, Spanned dest, int dstart, int dend) {
                String regex = "^[/a-zA-Z\u4e00-\u9fa5]{1,20}$";
                if (!source.toString().matches(regex)) {
                    return "";
                }
                return source;
            }
        }});
    }

}
